import math
import random
from datetime import timezone
from typing import Any
from traceback import format_exc
from django.core.handlers.wsgi import WSGIRequest
from django.http import JsonResponse, HttpResponse
from django.core.paginator import Paginator
from django.db import transaction, connection
from django.views import View
from django.db import connections

from rest_framework import status
from rest_framework.parsers import JSONParser
from jqgame.basegame import GameType
from jqgame.raffle import quanjushang_raffle

from warehouse.models import JuqiGood
from warehouse.serializers import JuqiGoodSerializer, CsSer
from jqpackage.models import UserPackageGoods
from uuid import uuid4

# from django.core.cache import cache
from .raffle import conn
from wuxianshang.models import (
    WuxianshangArgs,
    WuxianshangGame,
    WuxianshangGameGood,
    WuxianshangExtendBoss,
    WuxianshangExtendBossGood,
    create_boss_ticket,
    update_price_WuxianshangGame,
    wxs_raffle,
    get_wxs_args,
    WuxianshangRaffleRecord,
    TianjiangGoods,
    FeiqiuRecord,
)
from wxcloudrun.views import order_uuid

from .serializers import (
    WuxianshangGameSerializer,
    fill_WuxianshangGame,
    fill_WuxianshangRaffleRecord,
    WuxianshangArgsSerializer,
    WuxianshangRaffleRecordSerializer,
    OneGoodInfoSer,
    RecoderSer,
    TinajiangSer,
    TinajiangSerV2,
    RecoderSerV2,
    FeiqiuSer,
)

from wxuser.models import (
    UserHunJingRecord,
    UserPackage,
    UserPackageRecord,
    UserScoreRecord,
    UserStoredMoneyRecord,
    Users,
    UserOrder,
    add_user_order_goods,
)
from wxuser.serializers import save_UserPackages

from juqiadmin.models import (
    Finance,
    get_game_finance,
    get_wxuser_finance,
    update_finnce_profit,
)
from juqiadmin.auth import login_auth, JuqiUser, check_admin

from jqexception.jqexecption import (
    BalanceInsufficientErr,
    ExtendBossGoodErr,
    ValueErr,
    UnknowErr,
    RaffleBusyErr,
    RightErr,
    NullErr,
)

from wxcloudrun.models import get_table_datetime

from warehouse.models import GoodLevel

from django.core.cache import cache

import logging

from .raffle import QuanjushangRaffle
from django.db.models import Count, Sum
import json

qjs_raffle = QuanjushangRaffle()
logger = logging.getLogger("log")


class NewGameView(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        limit = int(request.GET.get("limit", 10))
        curPage = int(request.GET.get("page", 1))
        state = request.GET.get("state", None)
        game_name = request.GET.get("name", None)

        _game = WuxianshangGame.objects.filter(deleted=False)
        if state != None:
            _game = _game.filter(state=state)

        if game_name != None:
            _game = _game.filter(name=game_name)

        _game = _game.order_by("-id")

        pages = Paginator(_game, limit)
        paged = pages.page(curPage)

        game_data = WuxianshangGameSerializer(paged, many=True).data

        res = {
            "code": 0,
            "data": game_data,
            "data_count": pages.count,
            "page_count": pages.num_pages,
        }
        return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)


class GameGoodDetailView(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        uuid = request.GET.get("uuid", None)
        if uuid is None:
            raise ValueError

        game_good = WuxianshangGameGood.objects.filter(uuid=uuid).first()
        game_good_s = OneGoodInfoSer(game_good).data

        game_good_s["detail"]["good_weight"] = float(game_good_s["good_weight"]) / 100
        del game_good_s["good_weight"]

        game_good_s["good_level_uuid"] = game_good_s["level_uuid"]
        sale_able = 0
        if game_good_s["detail"]["sale_able"] == True:
            sale_able = 1
        game_good_s["sale_able"] = sale_able
        game_good_s["detail"]["sale_able"] = sale_able

        game_good_s["detail"]["price"] = game_good_s["detail"]["price"] / 100
        game_good_s["detail"]["recovery_price"] = (
            game_good_s["detail"]["recovery_price"] / 100
        )

        game_good_s["detail"]["cp"] = game_good_s["cp"]
        game_good_s["detail"]["good_level_uuid"] = game_good_s["level_uuid"]
        game_good_s["detail"]["score"] = game_good_s["score"]

        state = "0"

        _s = WuxianshangRaffleRecord.objects.filter(
            good_uuid=game_good.good_uuid
        ).first()
        if _s:
            state = "1"

        return JsonResponse(
            data={"code": 0, "data": game_good_s, "msg": "", "state": state},
            status=status.HTTP_200_OK,
        )


class GameGoodView(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        game_uuid = request.GET.get("game_uuid")
        good_type = int(request.GET.get("good_type", 0))
        info = (
            WuxianshangGameGood.objects.filter(deleted=False)
            .filter(game_uuid=game_uuid)
            .filter(good_type=good_type)
            .order_by("sort")
            .order_by("id")
        )
        res = {"code": 0, "data": OneGoodInfoSer(info, many=True).data}

        return JsonResponse(
            res,
            status=status.HTTP_200_OK,
            safe=False,
        )

    @login_auth
    @transaction.atomic
    def post(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        game: dict = JSONParser().parse(request)
        game_uuid = game.pop("game_uuid")
        level_uuid = game.pop("level_uuid")

        _g = WuxianshangGame.objects.filter(uuid=game_uuid).first()

        if not _g:
            raise NullErr

        level_info = GoodLevel.objects.filter(uuid=level_uuid).first()
        if not level_info:
            raise NullErr

        juqi_good = JuqiGood.objects.create(
            name=game.pop("good_name"),
            display_url=game.pop("display_url"),
            price=game.pop("price"),
            recovery_price=game.pop("recovery_price"),
            game_type="无限赏",
            detail=game.pop("detail"),
            level_title=level_info.title,
        )

        if game.pop("sale_able", 1) == 0:
            juqi_good.sale_able = False
            juqi_good.save()

        good_weight = game.pop("good_weight")
        if type(good_weight) == str:
            good_weight = float(str.replace(good_weight, "%", "")) * 100

        # 无限池赏品排序
        wxs_game_good_sort = 1
        wxs_game_good = (
            WuxianshangGameGood.objects.filter(deleted=False)
            .filter(game_uuid=game_uuid)
            .order_by("sort")
            .last()
        )
        if wxs_game_good is not None:
            wxs_game_good_sort = wxs_game_good.sort + 1

        cp = game.pop("cp", 0)
        score = game.pop("score", 0)
        WuxianshangGameGood.objects.create(
            game_uuid=game_uuid,
            good_uuid=juqi_good.uuid,
            good_weight=good_weight,
            level_uuid=level_info.uuid,
            good_rarity=level_info.title,
            sort=wxs_game_good_sort,
            good_type=level_info.method_type,
            cp=cp,
            score=score,
        )

        return JsonResponse(
            JuqiGoodSerializer(juqi_good, many=False).data,
            status=status.HTTP_201_CREATED,
        )

    @login_auth
    @transaction.atomic
    def put(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        body: dict = JSONParser().parse(request)

        uuid = body.pop("uuid", None)
        if uuid is None:
            raise ValueError

        game_good = WuxianshangGameGood.objects.filter(uuid=uuid, deleted=False).first()
        if game_good is None:
            raise ValueError

        game = WuxianshangGame.objects.filter(
            uuid=game_good.game_uuid, deleted=False
        ).first()
        if game.state == 1:
            return JsonResponse(
                data={"code": -1, "data": {}, "msg": "无法修改已上架的池子商品"},
                status=status.HTTP_200_OK,
            )

        price = body.pop("price", None)
        recovery_price = body.pop("recovery_price", None)
        cp = body.pop("cp", None)
        good_weight = body.pop("good_weight", None)
        if good_weight is not None and type(good_weight) == str:
            body["good_weight"] = float(str.replace(good_weight, "%", "")) * 100

        # WuxianshangGameGood.objects.update(**body)

        # WuxianshangGame.objects.filter(uuid=uuid).first()

        new_game_good = WuxianshangGameGood.objects.filter(
            uuid=uuid, deleted=False
        ).first()

        new_game_good.good_weight = body["good_weight"]
        if cp is not None:
            new_game_good.cp = cp

        score = body.pop("score", None)
        if score is not None:
            new_game_good.score = score

        new_game_good.save()

        jq_good = JuqiGood.objects.filter(uuid=new_game_good.good_uuid).first()
        if jq_good is None:
            raise ValueError

        jq_good.price = price
        jq_good.recovery_price = recovery_price
        jq_good.save()

        data = OneGoodInfoSer(new_game_good).data

        return JsonResponse(
            {"code": 0, "data": data, "msg": ""}, status=status.HTTP_200_OK
        )

    @login_auth
    @transaction.atomic
    def delete(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        body = JSONParser().parse(request)

        uuid = body.get("uuid", None)
        if uuid is None:
            raise ValueError

        game_good = WuxianshangGameGood.objects.filter(uuid=uuid).first()
        if game_good is None:
            raise ValueError

        game = WuxianshangGame.objects.filter(
            uuid=game_good.game_uuid, deleted=False
        ).first()
        if game.state:
            return JsonResponse(
                data={"code": -1, "data": {}, "msg": "无法修改已删除的池子商品"},
                status=status.HTTP_200_OK,
            )

        game_good.deleted = True
        game_good.save()

        return JsonResponse(
            data={"code": 0, "data": {}, "msg": ""}, status=status.HTTP_200_OK
        )


class BaodiCp(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "wxuser":
            raise RightErr

        openid = u.openid
        game_uuid = request.GET.get("game_uuid")
        user = Users.objects.filter(openid=openid).first()
        if not user:
            raise UnknowErr

        key = str(game_uuid) + str(user.uuid)
        baodi_cp = 0

        key_cache = conn.get(key)
        if key_cache:
            baodi_cp = int(key_cache)

        return JsonResponse(
            data={
                "code": 0,
                "num": baodi_cp,
            },
            status=status.HTTP_200_OK,
        )


class Tjnum(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "wxuser":
            raise RightErr

        game_uuid = request.GET.get("game_uuid")

        # 当前进度
        count = 0

        game = WuxianshangGame.objects.filter(uuid=game_uuid).first()
        if game.tianjiangsb == 1:
            count = game.count % game.tianjiang_num

        return JsonResponse(
            data={
                "code": 0,
                "num": count,
            },
            status=status.HTTP_200_OK,
        )


class GameDetailView(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        uuid = request.GET.get("uuid", None)
        if uuid is None:
            raise ValueError

        game = WuxianshangGame.objects.filter(uuid=uuid).first()
        if game is None:
            raise ValueError

        game_s = WuxianshangGameSerializer(game).data
        game_s["price"] = game_s["price"] / 100

        return JsonResponse(
            data={"code": 0, "data": game_s, "msg": ""}, status=status.HTTP_200_OK
        )


class GameView(View):
    def setup(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        super().setup(request, *args, **kwargs)

    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        #   req query params：
        #   - `many`  查询所有商品
        #   - `page` 分页
        #   - `num`  查询个数
        #   - `uuid`  good uuid
        #   - `name`  商品名称
        _list = request.GET.get("list", None)
        if not _list:
            # query single good
            game_uuid = request.GET.get("uuid", None)
            game_name = request.GET.get("name", None)
            state = request.GET.get("state", 1)

            g = None
            if game_uuid:
                g = (
                    WuxianshangGame.objects.filter(uuid=game_uuid)
                    .filter(deleted=False)
                    .filter(state=state)
                    .first()
                )
            elif game_name:
                g = (
                    WuxianshangGame.objects.filter(name=game_name)
                    .filter(deleted=False)
                    .filter(state=state)
                    .first()
                )
            if not g:
                raise NullErr
            g_s = WuxianshangGameSerializer(g)
            game = fill_WuxianshangGame(g_s.data)
            return JsonResponse(game, status=status.HTTP_200_OK)
        else:
            page = int(request.GET.get("page", None))
            num = min(50, int(request.GET.get("num", None)))

            ip_family = request.GET.get("ip_family", None)
            state = request.GET.get("state", None)

            _objs = WuxianshangGame.objects

            if ip_family != None:
                _objs = _objs.filter(ip_family=ip_family)

            if state != None:
                _objs = _objs.filter(state=state)

            all_game = _objs.filter(deleted=False)

            p = Paginator(all_game, num)
            games = p.get_page(page).object_list
            detail_games = []
            for g in games:
                g_s = WuxianshangGameSerializer(g)
                try:
                    game = fill_WuxianshangGame(g_s.data)
                except:
                    logger.exception(
                        f"fill_WuxianshangGame game fail : {game.uuid} {format_exc()}"
                    )
                else:
                    detail_games.append(game)
            return JsonResponse(detail_games, status=status.HTTP_200_OK, safe=False)

    @login_auth
    @transaction.atomic
    def post(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        game: dict = JSONParser().parse(request)
        if int(game["score_pay"]) == 1:
            game["price"] = game["price"] / 100

        game_s = WuxianshangGameSerializer(data=game)

        game_s.is_valid(raise_exception=True)
        game_s = game_s.save()
        game_ = WuxianshangGameSerializer(game_s, many=False).data

        return JsonResponse(game_, status=status.HTTP_201_CREATED)

    @login_auth
    @transaction.atomic
    def put(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr

        WuxianshangGame.objects.select_for_update()

        body: dict = JSONParser().parse(request)

        g = (
            WuxianshangGame.objects.filter(uuid=body["uuid"])
            .filter(deleted=False)
            .first()
        )

        if not g:
            raise NullErr

        # 预生成10w发的奖品列表
        if body.get("state", 0) == 1:
            good_len = qjs_raffle.get_good_len(str(g.uuid))
            if good_len == 0 or good_len < 5000:
                qjs_raffle.init_prize(str(g.uuid))

        del body["uuid"]
        for k, v in body.items():
            setattr(g, k, v)
        g.clean()
        g.save()

        _game_s = WuxianshangGameSerializer(g)
        detail_game_info = fill_WuxianshangGame(_game_s.data)

        return JsonResponse(
            detail_game_info,
            status=status.HTTP_200_OK,
        )

    @login_auth
    @transaction.atomic
    def delete(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u = kwargs["user_info"]
        if u.type != "admin":
            raise RightErr
        WuxianshangGame.objects.select_for_update()
        WuxianshangGameGood.objects.select_for_update()

        body: dict = JSONParser().parse(request)

        game = (
            WuxianshangGame.objects.filter(uuid=body["uuid"])
            .filter(deleted=False)
            .first()
        )

        if not game:
            raise NullErr

        WuxianshangGameGood.objects.filter(game_uuid=body["uuid"]).update(deleted=True)

        if game.extend_type_boss:
            WuxianshangExtendBoss.objects.filter(game_uuid=body["uuid"]).update(
                deleted=True
            )
            WuxianshangExtendBossGood.objects.filter(game_uuid=body["uuid"]).update(
                deleted=True
            )

        game.deleted = True
        game.save()

        return JsonResponse(
            {"code": 0, "data": f"del {game['uuid']}"}, status=status.HTTP_200_OK
        )

    @login_auth
    def head(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        update_time = get_table_datetime(WuxianshangGameGood._meta.db_table)
        timestamp = update_time.replace(tzinfo=timezone.utc).timestamp()
        return HttpResponse(
            status=status.HTTP_200_OK, headers={"Last-Modified": update_time}
        )


def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [dict(zip(columns, row)) for row in cursor.fetchall()]


class RaffleView(View):
    def setup(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        super().setup(request, *args, **kwargs)

    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        # _list = request.GET.get("list", None)
        # if not _list:
        #     raise ValueError

        page = request.GET.get("page", 1)
        limit = request.GET.get("limit", 50)
        game_uuid = request.GET.get("game_uuid", None)
        recoder_type = int(request.GET.get("recoder_type", 0))
        # 0普通 1欧皇 2保底 3天降
        if not game_uuid:
            raise ValueError
        game_uuid = game_uuid.replace("-", "")
        good_type = None
        good_level_title = None

        if isinstance(page, str):
            page = int(page)

        if isinstance(limit, str):
            limit = int(limit)

        # search_dict['good_type'] = 0
        if recoder_type == 0:
            good_type = 0

        elif recoder_type == 1:
            # search_dict["level_uuid"] = _level.uuid
            good_type = 0
            good_level_title = "传说款"

        # 查看保底
        elif recoder_type == 2:
            good_type = 1
        elif recoder_type == 3:
            good_type = 2
        _rocder = {}
        _rocder_count = {}
        with connection.cursor() as cursor:
            if good_level_title is None:
                _sql = """
                            SELECT
                              users.nickname AS user_nickname,
                              record.raffle_count AS raffle_count,
                              record.createdAt AS createdAt,
                              users.head_url AS user_head_url,
                              good.name AS good_name,
                              good_level.img_url AS level_url
                            FROM
                              WuxianshangRaffleRecord record
                              LEFT JOIN WuxianshangGameGood game_good ON game_good.good_uuid = record.good_uuid AND game_good.good_type = %s
                              LEFT JOIN Users users ON users.uuid = record.user_uuid
                              LEFT JOIN JuqiGood good ON good.uuid = record.good_uuid
                              LEFT JOIN GoodLevel good_level ON good_level.uuid = game_good.level_uuid
                            WHERE
                              game_good.game_uuid = %s
                              AND game_good.deleted = 0
                            LIMIT  %s,  %s;
    
                """
                _sql_count = """
                            SELECT
                              COUNT(*) AS count
                            FROM
                              WuxianshangRaffleRecord record
                              LEFT JOIN WuxianshangGameGood game_good ON game_good.good_uuid = record.good_uuid AND game_good.good_type = %s
                            WHERE
                              record.game_uuid = %s
                              AND record.deleted = 0;
                """
                cursor.execute(_sql_count, [good_type, game_uuid])
                _rocder_count = dictfetchall(cursor)

                sum = _rocder_count[0]["count"]
                __page = page - 1
                if __page < 0:
                    __page = 0
                count = sum - (__page * limit)
                offset = count - limit

                if offset < 0:
                    offset = 0

                logger.info(
                    f"uuid -> {game_uuid} || sum -> {sum}, count -> {count}, offset -> {offset}, limit -> {limit}, page -> {page}"
                )
                cursor.execute(
                    _sql,
                    [
                        good_type,
                        game_uuid,
                        offset,
                        limit,
                    ],
                )
                _rocder = dictfetchall(cursor)
                _rocder.reverse()

            else:
                _sql = """
                SELECT
                  users.nickname AS user_nickname,
                  record.raffle_count AS raffle_count,
                  record.createdAt AS createdAt,
                  users.head_url AS user_head_url,
                  good.name AS good_name,
                  good_level.img_url AS level_url
                FROM
                  WuxianshangRaffleRecord record
                  LEFT JOIN WuxianshangGameGood game_good ON game_good.good_uuid = record.good_uuid AND game_good.good_type = %s
                  LEFT JOIN Users users ON users.uuid = record.user_uuid
                  LEFT JOIN JuqiGood good ON good.uuid = record.good_uuid
                  LEFT JOIN GoodLevel good_level ON good_level.uuid = game_good.level_uuid
                WHERE
                  record.game_uuid = %s
                  AND record.deleted = 0
                  AND good.level_title = %s
                LIMIT  %s,  %s;
                """
                _sql_count = """
                            SELECT
                              COUNT(*) AS count
                            FROM
                              WuxianshangRaffleRecord record
                              LEFT JOIN WuxianshangGameGood game_good ON game_good.good_uuid = record.good_uuid AND game_good.good_type = %s
                              LEFT JOIN JuqiGood good ON good.uuid = record.good_uuid
                            WHERE
                              record.game_uuid = %s
                              AND record.deleted = 0
                              AND good.level_title = %s
                """
                cursor.execute(_sql_count, [good_type, game_uuid, good_level_title])
                _rocder_count = dictfetchall(cursor)

                sum = _rocder_count[0]["count"]
                __page = page - 1
                if __page < 0:
                    __page = 0
                count = sum - (__page * limit)
                offset = count - limit

                if offset < 0:
                    offset = 0

                cursor.execute(
                    _sql,
                    [good_type, game_uuid, good_level_title, offset, limit],
                )
                _rocder = dictfetchall(cursor)
                _rocder.reverse()
                # pages = Paginator(_rocder, limit)
            # paged = pages.page(page)

        _data = RecoderSerV2(_rocder, many=True).data
        res = {"code": 0, "data": _data, "page_count": _rocder_count[0].get("count")}
        return JsonResponse(res, status=status.HTTP_200_OK, safe=False)

    @login_auth
    @transaction.atomic
    def post(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u: JuqiUser = kwargs["user_info"]
        if u.type != "wxuser":
            raise RightErr

        openid = u.openid

        body: dict = JSONParser().parse(request)
        game_uuid = body.pop("game_uuid")
        # pay_type = body.pop("pay_type")
        stored_money = body.pop("stored_money", 0)
        hunjing = body.pop("hunjing", 0)
        score = body.pop("score", 0)
        raffle_count = body.pop("raffle_count", 1)

        user = (
            Users.objects.filter(openid=openid)
            .filter(deleted=False)
            .select_for_update()
            .first()
        )
        if not user:
            raise NullErr

        game = (
            WuxianshangGame.objects.filter(uuid=game_uuid)
            .filter(deleted=False)
            .select_for_update()
            .first()
        )
        if not game:
            raise NullErr

        if game.state != 1:
            raise UnknowErr

        if game.score_pay == 1:
            if stored_money == 1 or hunjing == 1:
                raise UnknowErr

        # used for pay
        wuxianshang_finance = get_game_finance(GameType.wuxianshang)
        sum_price = game.price * raffle_count

        user_order = UserOrder(
            user_uuid=user.uuid,
            game_uuid=game_uuid,
            son_uuid=game.uuid,
            orderid=order_uuid(prefix="CS_"),
            game_name=game.name,
            price=game.price,
            num=raffle_count,
            game_type=GameType.wuxianshang.value,
        )

        currency = 0
        if stored_money == 1:
            currency += user.stored_money
        if hunjing == 1:
            currency += user.hunjing
        if score == 1:
            currency += user.score

        sum_price = game.price * raffle_count
        dzf = game.price * raffle_count
        if currency < sum_price:
            res = {"code": -1, "msg": "余额不足"}
            return JsonResponse(res, status=(status.HTTP_200_OK), safe=False)

        if stored_money == 1:
            # 如果余额小于支付金额 扣完余额
            if user.stored_money < sum_price:
                user_order.money = user.stored_money
                _old = user.stored_money
                _new = _old - user.stored_money
                dzf = dzf - user.stored_money
                user.stored_money = _new
            else:
                user_order.money = dzf
                _old = user.stored_money
                _new = _old - dzf
                user.stored_money = _new
                dzf = 0

            zfje = user_order.money

            _record = {
                "user_uuid": user.uuid,
                "stored_money": -zfje,
                "old_stored_money": _old,
                "new_stored_money": _new,
                "detail": f"{game.name}抽奖{raffle_count}次",
            }
            UserStoredMoneyRecord.objects.create(**_record)

        if hunjing == 1 and dzf > 0:
            # 如果余额支付存在 并且dzf不等于0
            if stored_money == 1 and dzf != 0:
                # 如果待支付余额大于魂晶 报错
                if dzf > user.hunjing:
                    raise UnknowErr
                # 如果小于魂晶执行
                else:
                    user_order.hunjing = dzf
                    _old = user.hunjing
                    _new = _old - dzf
                    dzf = dzf - user_order.hunjing
                    user.hunjing = _new

            # 条件不满足直接扣除
            else:
                user_order.hunjing = sum_price
                _old = user.hunjing
                _new = _old - sum_price
                user.hunjing = _new
                dzf = 0

            zfje = user_order.hunjing
            _record = {
                "user_uuid": user.uuid,
                "hunjing": -zfje,
                "old_hunjing": _old,
                "new_hunjing": _new,
                "detail": f"{game.name}抽奖{raffle_count} 次",
            }
            UserHunJingRecord(**_record).save()

        if score == 1 and dzf > 0:
            if stored_money == 1 or hunjing == 1:
                raise UnknowErr

            user_order.score = sum_price
            _old = user.score
            _new = _old - sum_price
            user.score = _new
            dzf = 0

            zfje = user_order.score
            _record = {
                "user_uuid": user.uuid,
                "score": -zfje,
                "old_score": _old,
                "new_score": _new,
                "detail": f"{game.name} 抽奖 {raffle_count} 次",
            }
            UserScoreRecord(**_record).save()

        if dzf != 0:
            raise BalanceInsufficientErr

        if score != 1:
            wuxianshang_finance.all_raffle_income += sum_price

        user_finace = get_wxuser_finance(
            user_uuid=user.uuid, gameType=GameType.wuxianshang, game_uuid=game.uuid
        )
        if score != 1:
            user_finace.all_raffle_income += sum_price

        # raffle
        sum_value = 0
        res_goods = []
        good_uuid_dict = {}
        packages_info = []
        next_wuxianshang_all_raffle_cost = 0

        raffle_goods, raffle_good_list = qjs_raffle.qjs_raffle(
            user.id, user.uuid, str(game.uuid), raffle_count
        )
        good_uuid_list = []

        for k, count in raffle_goods.items():
            # 出参 juqigood_uuid  count 数量
            good = (
                JuqiGood.objects.filter(uuid=k)
                .filter(deleted=False)
                .select_for_update()
                .first()
            )
            if not good:
                raise NullErr

            for i in range(count):
                good_uuid_list.append(k)

            # 返积分
            if game.is_fjf == 1:
                _goodscore = WuxianshangGameGood.objects.filter(good_uuid=k).first()
                if _goodscore.score >= 1:
                    send_socre = _goodscore.score * count
                    _old = user.score
                    _new = user.score + send_socre
                    user.score = _new
                    user_finace.all_raffle_cost += send_socre
                    next_wuxianshang_all_raffle_cost += send_socre
                    # 创建记录
                    _record = {
                        "user_uuid": user.uuid,
                        "score": send_socre,
                        "old_score": _old,
                        "new_score": _new,
                        "detail": f"{game.name} 返还赏豆  {send_socre}  ",
                    }
                    UserScoreRecord(**_record).save()

            # sum_value += count * good.price
            sum_value += count * good.recovery_price

            good_s = CsSer(good)
            next_wuxianshang_all_raffle_cost += count * good.recovery_price
            # 字典赏品数据
            good_uuid_dict[k] = good_s.data

        random.shuffle(good_uuid_list)

        # 保底模式
        if game.baodi == 1:
            key = str(game_uuid) + str(user.uuid)
            key_cache = conn.get(key)
            cp_num = 0
            if key_cache:
                cp_num += int(key_cache)

            for k in raffle_good_list:
                _good = (
                    WuxianshangGameGood.objects.filter(good_uuid=k)
                    .filter(game_uuid=game_uuid)
                    .first()
                )
                if _good.cp != -1 and _good != 0:
                    cp_num += _good.cp
                    if cp_num >= game.baodi_cp:
                        # 派奖清零
                        baodi_goods = (
                            WuxianshangGameGood.objects.filter(game_uuid=game_uuid)
                            .filter(deleted=False)
                            .filter(good_type=1)
                            .all()
                        )
                        _send_good = random.choice(baodi_goods)
                        # 给这个用户
                        _g = JuqiGood.objects.filter(uuid=_send_good.good_uuid).first()

                        good_s = CsSer(_g)
                        next_wuxianshang_all_raffle_cost += _g.recovery_price
                        sum_value += _g.recovery_price
                        # 字典赏品数据
                        good_uuid_dict[_g.uuid] = good_s.data

                        raffle_good_list.append(_g.uuid)
                        if key_cache:
                            conn.delete(key)
                        cp_num = 0
                else:
                    # 爆出赏品清0cp值
                    cp_num = 0

            conn.set(key, cp_num, 604800)

        # 天降神兵模式
        if game.tianjiangsb == 1:
            # 触发神兵
            start_count = game.count
            end_count = start_count + raffle_count

            for item in range(start_count + 1, end_count + 1):
                # 触发神兵
                if item % game.tianjiang_num == 0:
                    sb_goods = (
                        WuxianshangGameGood.objects.filter(deleted=False)
                        .filter(game_uuid=game_uuid)
                        .filter(good_type=2)
                    )
                    # 派发的神兵
                    send_good = random.choice(sb_goods)
                    # 获取这个抽奖区间的人
                    send_user = (
                        WuxianshangRaffleRecord.objects.filter(game_uuid=game_uuid)
                        .filter(raffle_count__gt=item - game.tianjiang_num)
                        .filter(raffle_count__lte=item)
                        .order_by("?")
                        .first()
                    )
                    # 获取赏品价值
                    price_good = JuqiGood.objects.filter(
                        uuid=send_good.good_uuid
                    ).first()
                    next_wuxianshang_all_raffle_cost += price_good.recovery_price
                    # 放入背包
                    if send_user.user_uuid == user.uuid:
                        user.package_amount += price_good.recovery_price
                        user_finace.all_raffle_cost += price_good.recovery_price

                        _c = (
                            UserPackageGoods.objects.filter(user_uuid=user.uuid)
                            .filter(game_uuid=game_uuid)
                            .filter(game_type=GameType.wuxianshang.value)
                            .filter(order_num=send_user.raffle_count)
                            .first()
                        )

                        UserPackageGoods.objects.create(
                            user_uuid=user.uuid,
                            good_uuid=price_good.uuid,
                            good_level_title=price_good.level_title,
                            game_type=GameType.wuxianshang.value,
                            game_uuid=game_uuid,
                            order_uuid=_c.order_uuid,
                            order_num=send_user.raffle_count,
                        )

                        TianjiangGoods.objects.create(
                            user_uuid=user.uuid,
                            game_uuid=game_uuid,
                            good_uuid=price_good.uuid,
                            count=send_user.raffle_count,
                            start_count=(item - game.tianjiang_num) + 1,
                            end_count=item,
                        )

                    else:
                        _user = Users.objects.filter(uuid=send_user.user_uuid).first()
                        _user.package_amount += price_good.recovery_price
                        send_user_finace = get_wxuser_finance(
                            user_uuid=_user.uuid,
                            gameType=GameType.wuxianshang,
                            game_uuid=game.uuid,
                        )
                        send_user_finace.all_raffle_cost += price_good.recovery_price
                        send_user_finace.all_raffle_profit = (
                            send_user_finace.all_raffle_income
                            - send_user_finace.all_raffle_cost
                        )
                        send_user_finace.save()

                        _c = (
                            UserPackageGoods.objects.filter(user_uuid=_user.uuid)
                            .filter(game_uuid=game_uuid)
                            .filter(game_type=GameType.wuxianshang.value)
                            .filter(order_num=send_user.raffle_count)
                            .first()
                        )

                        UserPackageGoods.objects.create(
                            user_uuid=_user.uuid,
                            good_uuid=price_good.uuid,
                            good_level_title=price_good.level_title,
                            game_type=GameType.wuxianshang.value,
                            game_uuid=game_uuid,
                            order_uuid=_c.order_uuid,
                            order_num=send_user.raffle_count,
                        )

                        TianjiangGoods.objects.create(
                            user_uuid=_user.uuid,
                            game_uuid=game_uuid,
                            good_uuid=price_good.uuid,
                            count=send_user.raffle_count,
                            start_count=(item - game.tianjiang_num) + 1,
                            end_count=item,
                        )
                        _user.save()

        save_UserPackages(
            raffle_good_list,
            game_type=GameType.wuxianshang,
            game=game,
            user_obj=user,
            user_order_uuid=user_order.uuid,
        )

        # 非酋模式
        if game.feiqiu == 1:
            # 触发非酋模式
            start_count = game.count
            end_count = start_count + raffle_count

            for item in range(start_count + 1, end_count + 1):
                # 触发非酋

                if item % game.feiqiu_num == 0:
                    sb_goods = (
                        WuxianshangGameGood.objects.filter(deleted=False)
                        .filter(game_uuid=game_uuid)
                        .filter(good_type=3)
                    )
                    # 派发的非酋
                    send_good = random.choice(sb_goods)

                    # 获取这个抽奖区间的人进行排序
                    send_user = (
                        UserPackageGoods.objects.filter(game_uuid=game_uuid)
                        .filter(order_num__gt=item - game.feiqiu_num)
                        .filter(order_num__lte=item)
                        .extra(
                            select={
                                "num": "UserOrder.num",
                                "money": "UserOrder.money",
                                "hunjing": "UserOrder.hunjing",
                                "recovery_price": "JuqiGood.recovery_price",
                            },
                            tables=["JuqiGood", "UserOrder"],
                            where=[
                                "UserOrder.uuid=UserPackageGoods.order_uuid",
                                "JuqiGood.uuid=UserPackageGoods.good_uuid",
                            ],
                        )
                        .values(
                            "recovery_price", "money", "hunjing", "num", "user_uuid"
                        )
                    )

                    _send = {}
                    for feiqiu_item in send_user:
                        if _send.get(feiqiu_item["user_uuid"]):
                            _send[feiqiu_item["user_uuid"]] += (
                                (feiqiu_item["money"] + feiqiu_item["hunjing"])
                                / feiqiu_item["num"]
                            ) - feiqiu_item["recovery_price"]
                        else:
                            _send[feiqiu_item["user_uuid"]] = (
                                (feiqiu_item["money"] + feiqiu_item["hunjing"])
                                / feiqiu_item["num"]
                            ) - feiqiu_item["recovery_price"]

                    a1 = dict(sorted(_send.items(), key=lambda x: x[1], reverse=True))

                    user_uuid = ""
                    paijiang = True
                    for _s, _value in a1.items():
                        if _value <= 0:
                            paijiang = False
                        user_uuid = _s
                        break

                    if paijiang == True:
                        # 获取赏品价值
                        price_good = JuqiGood.objects.filter(
                            uuid=send_good.good_uuid
                        ).first()
                        next_wuxianshang_all_raffle_cost += price_good.recovery_price
                        # 放入背包
                        if user_uuid == user.uuid:
                            user.package_amount += price_good.recovery_price
                            user_finace.all_raffle_cost += price_good.recovery_price

                            UserPackageGoods.objects.create(
                                user_uuid=user.uuid,
                                good_uuid=price_good.uuid,
                                good_level_title=price_good.level_title,
                                game_type=GameType.wuxianshang.value,
                                game_uuid=game_uuid,
                                order_uuid=uuid4(),
                                order_num=0,
                            )

                            FeiqiuRecord.objects.create(
                                user_uuid=user.uuid,
                                game_uuid=game_uuid,
                                good_uuid=price_good.uuid,
                                start_count=(item - game.feiqiu_num) + 1,
                                end_count=item,
                            )

                        else:
                            _user = Users.objects.filter(uuid=user_uuid).first()
                            _user.package_amount += price_good.recovery_price
                            send_user_finace = get_wxuser_finance(
                                user_uuid=_user.uuid,
                                gameType=GameType.wuxianshang,
                                game_uuid=game.uuid,
                            )
                            send_user_finace.all_raffle_cost += (
                                price_good.recovery_price
                            )
                            send_user_finace.all_raffle_profit = (
                                send_user_finace.all_raffle_income
                                - send_user_finace.all_raffle_cost
                            )
                            send_user_finace.save()

                            UserPackageGoods.objects.create(
                                user_uuid=_user.uuid,
                                good_uuid=price_good.uuid,
                                good_level_title=price_good.level_title,
                                game_type=GameType.wuxianshang.value,
                                game_uuid=game_uuid,
                                order_uuid=uuid4(),
                                order_num=0,
                            )

                            FeiqiuRecord.objects.create(
                                user_uuid=_user.uuid,
                                game_uuid=game_uuid,
                                good_uuid=price_good.uuid,
                                start_count=(item - game.feiqiu_num) + 1,
                                end_count=item,
                            )
                            _user.save()

        # 循环奖品uuid列表
        for good_uuid in raffle_good_list:
            res_goods.append(good_uuid_dict[good_uuid])

        raffle_res = {}
        raffle_res["sum_value"] = sum_value
        raffle_res["goods"] = res_goods

        user_finace.all_raffle_cost += sum_value

        wuxianshang_finance.all_raffle_cost += next_wuxianshang_all_raffle_cost

        update_finnce_profit(user_finace)
        update_finnce_profit(wuxianshang_finance)
        # start save to package, deal finance, user money

        # 更新用户赏柜价值
        user.package_amount = user.package_amount + sum_value

        Finance.objects.bulk_update(
            [wuxianshang_finance, user_finace],
            ["all_raffle_income", "all_raffle_cost", "all_raffle_profit"],
        )
        user.save()

        game.count += raffle_count
        game.save()
        user_order.save()
        # _boss_prize_exchange(game)

        # add_user_order_goods(user_order.uuid, good_uuid_list)

        remaining_good_count = qjs_raffle.get_good_len(str(game.uuid))
        if remaining_good_count < 5000:
            qjs_raffle.init_prize(str(game.uuid))

        return JsonResponse(
            raffle_res,
            status=status.HTTP_200_OK,
            json_dumps_params={"ensure_ascii": False},
        )


class RaffleV2View(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        offset = request.GET.get("offset", 0)
        limit = request.GET.get("limit", 50)
        game_uuid = request.GET.get("game_uuid", None)
        recoder_type = int(request.GET.get("recoder_type", 0))
        # 0普通 1欧皇 2保底 3天降
        if not game_uuid:
            raise ValueError
        game_uuid = game_uuid.replace("-", "")
        good_type = 0
        good_level_title = ""
        if recoder_type == 0:
            good_type = 0

        if recoder_type == 1:
            good_type = 0
            good_level_title = "传说款"

        if isinstance(offset, str):
            offset = int(offset)

        if isinstance(limit, str):
            limit = int(limit)

        if offset <= 0 or limit <= 0:
            res = {"code": 0, "data": []}
            return JsonResponse(res, status=status.HTTP_200_OK, safe=False)
        # 查看保底
        if recoder_type == 2:
            good_type = 1
        if recoder_type == 3:
            good_type = 2
        _rocder = {}
        with connection.cursor() as cursor:
            if recoder_type == 0:
                _offset = offset - limit

                if _offset < 0:
                    _offset = 0

                select_range = range(_offset + 1, offset + 1)
                _sql = ""
                _sql_parm = []
                if len(select_range) <= 0:
                    raise UnknowErr

                for raffle_count in select_range:
                    _sql_parm.append(game_uuid)
                    _sql_parm.append(good_type)
                    _sql_parm.append(raffle_count)
                    _sql += (
                        f"SELECT users.nickname AS user_nickname, record.raffle_count AS raffle_count, "
                        "record.createdAt AS createdAt, users.head_url AS user_head_url, good.name AS good_name, "
                        "good_level.img_url AS level_url FROM WuxianshangRaffleRecord record LEFT JOIN "
                        "WuxianshangGameGood game_good ON game_good.good_uuid = record.good_uuid LEFT JOIN Users "
                        "users ON users.uuid = record.user_uuid LEFT JOIN JuqiGood good ON good.uuid = "
                        "record.good_uuid LEFT JOIN GoodLevel good_level ON good_level.uuid = "
                        "game_good.level_uuid WHERE game_good.game_uuid = %s AND game_good.good_type = %s AND "
                        "record.raffle_count = %s AND game_good.deleted = 0"
                    )
                    if raffle_count != offset:
                        _sql += " UNION ALL "
                _sql += ";"
                cursor.execute(
                    _sql,
                    _sql_parm,
                )
                _rocder = dictfetchall(cursor)
                _rocder.reverse()
            elif recoder_type == 1 and good_level_title != "":
                _sql = """
                    SELECT
                      users.nickname AS user_nickname,
                      record.raffle_count AS raffle_count,
                      record.createdAt AS createdAt,
                      users.head_url AS user_head_url,
                      good.name AS good_name,
                      good_level.img_url AS level_url
                    FROM
                      WuxianshangRaffleRecord record
                      LEFT JOIN WuxianshangGameGood game_good ON game_good.good_uuid = record.good_uuid
                      LEFT JOIN Users users ON users.uuid = record.user_uuid
                      LEFT JOIN JuqiGood good ON good.uuid = record.good_uuid
                      LEFT JOIN GoodLevel good_level ON good_level.uuid = game_good.level_uuid
                    WHERE
                      record.game_uuid = %s
                      AND game_good.good_type = %s
                      AND record.deleted = 0
                      AND good.level_title = %s
                    ORDER BY record.raffle_count
                    LIMIT  %s,  %s;
                """

                _offset = offset - limit

                if _offset < 0:
                    _offset = 0
                    limit = offset

                cursor.execute(
                    _sql,
                    [game_uuid, good_type, good_level_title, _offset, limit],
                )
                _rocder = dictfetchall(cursor)
                _rocder.reverse()
            elif recoder_type == 2 or recoder_type == 3:
                _sql = """
                    SELECT
                      users.nickname AS user_nickname,
                      record.raffle_count AS raffle_count,
                      record.createdAt AS createdAt,
                      users.head_url AS user_head_url,
                      good.name AS good_name,
                      good_level.img_url AS level_url
                    FROM
                      WuxianshangRaffleRecord record
                      LEFT JOIN WuxianshangGameGood game_good ON game_good.good_uuid = record.good_uuid
                      LEFT JOIN Users users ON users.uuid = record.user_uuid
                      LEFT JOIN JuqiGood good ON good.uuid = record.good_uuid
                      LEFT JOIN GoodLevel good_level ON good_level.uuid = game_good.level_uuid
                    WHERE
                      game_good.game_uuid = %s
                      AND game_good.good_type = %s
                      AND game_good.deleted = 0
                    LIMIT  %s,  %s;
                                """

                _offset = offset - limit

                if _offset < 0:
                    _offset = 0
                    limit = offset

                cursor.execute(
                    _sql,
                    [
                        game_uuid,
                        good_type,
                        _offset,
                        limit,
                    ],
                )
                _rocder = dictfetchall(cursor)
                _rocder.reverse()
            else:
                raise UnknowErr

        _data = RecoderSerV2(_rocder, many=True).data
        res = {"code": 0, "data": _data}
        return JsonResponse(res, status=status.HTTP_200_OK, safe=False)


class RaffleV2CountView(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        game_uuid = request.GET.get("game_uuid", None)
        recoder_type = int(request.GET.get("recoder_type", 0))
        # 0普通 1欧皇 2保底 3天降
        if not game_uuid:
            raise ValueError
        game_uuid = game_uuid.replace("-", "")
        good_type = 0
        good_level_title = ""

        if recoder_type == 0:
            good_type = 0

        elif recoder_type == 1:
            good_type = 0
            good_level_title = "传说款"

        # 查看保底
        elif recoder_type == 2:
            good_type = 1
        elif recoder_type == 3:
            good_type = 2
        _rocder_count = {}

        if good_level_title is None or good_level_title == "":
            wuxianshang_game = WuxianshangGame.objects.filter(uuid=game_uuid).first()
            if recoder_type == 0:
                page_count = wuxianshang_game.count
                res = {"code": 0, "page_count": page_count}
                return JsonResponse(res, status=status.HTTP_200_OK, safe=False)
            else:
                with connection.cursor() as cursor:
                    _sql_count = """
                        SELECT
                          COUNT(*) AS count
                        FROM
                          WuxianshangRaffleRecord record
                          LEFT JOIN WuxianshangGameGood game_good ON game_good.good_uuid = record.good_uuid
                        WHERE
                          record.game_uuid = %s
                          AND game_good.good_type = %s
                          AND record.deleted = 0;
                        """
                    cursor.execute(_sql_count, [game_uuid, good_type])
                    _rocder_count = dictfetchall(cursor)
        else:
            with connection.cursor() as cursor:
                _sql_count = """
                    SELECT
                      COUNT(*) AS count
                    FROM
                      WuxianshangRaffleRecord record
                      LEFT JOIN WuxianshangGameGood game_good ON game_good.good_uuid = record.good_uuid 
                      LEFT JOIN JuqiGood good ON good.uuid = record.good_uuid
                    WHERE
                      record.game_uuid = %s
                      AND game_good.good_type = %s
                      AND record.deleted = 0
                      AND good.level_title = %s
                    """
                cursor.execute(_sql_count, [game_uuid, good_type, good_level_title])
                _rocder_count = dictfetchall(cursor)

        res = {"code": 0, "page_count": _rocder_count[0].get("count")}
        return JsonResponse(res, status=status.HTTP_200_OK, safe=False)


class TianjiangRecoderView(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        #   req query params：
        #   - `many`  查询所有商品
        game_uuid = request.GET.get("game_uuid")
        limit = int(request.GET.get("limit", 10))
        curPage = int(request.GET.get("page", 1))

        _recoder = (
            TianjiangGoods.objects.filter(game_uuid=game_uuid)
            .extra(
                select={
                    "user_nickname": "Users.nickname",
                    "user_head_url": "Users.head_url",
                    "good_name": "JuqiGood.name",
                    "level_url": "GoodLevel.img_url",
                },
                tables=["Users", "JuqiGood", "GoodLevel"],
                where=[
                    "TianjiangGoods.user_uuid=Users.uuid",
                    "TianjiangGoods.good_uuid=JuqiGood.uuid",
                    "JuqiGood.level_title=GoodLevel.title",
                ],
            )
            .values(
                "count",
                "start_count",
                "end_count",
                "user_nickname",
                "user_head_url",
                "good_name",
                "level_url",
                "createdAt",
            )
        )

        pages = Paginator(_recoder, limit)
        paged = pages.page(curPage)

        game_data = TinajiangSerV2(paged, many=True).data
        res = {
            "code": 0,
            "data": game_data,
            "data_count": pages.count,
            "page_count": pages.num_pages,
        }
        return JsonResponse(res, status=status.HTTP_200_OK, safe=False)


class FeiqiuRecoderView(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        #   req query params：
        #   - `many`  查询所有商品
        game_uuid = request.GET.get("game_uuid")
        limit = int(request.GET.get("limit", 10))
        curPage = int(request.GET.get("page", 1))

        _recoder = (
            FeiqiuRecord.objects.filter(game_uuid=game_uuid)
            .extra(
                select={
                    "user_nickname": "Users.nickname",
                    "user_head_url": "Users.head_url",
                    "good_name": "JuqiGood.name",
                    "level_url": "GoodLevel.img_url",
                },
                tables=["Users", "JuqiGood", "GoodLevel"],
                where=[
                    "FeiqiuRecord.user_uuid=Users.uuid",
                    "FeiqiuRecord.good_uuid=JuqiGood.uuid",
                    "JuqiGood.level_title=GoodLevel.title",
                ],
            )
            .values(
                "start_count",
                "end_count",
                "user_nickname",
                "user_head_url",
                "good_name",
                "level_url",
                "createdAt",
            )
        )

        pages = Paginator(_recoder, limit)
        paged = pages.page(curPage)

        game_data = FeiqiuSer(paged, many=True).data
        res = {
            "code": 0,
            "data": game_data,
            "data_count": pages.count,
            "page_count": pages.num_pages,
        }
        return JsonResponse(res, status=status.HTTP_200_OK, safe=False)


class FeiqiuRecoderDetailView(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        game_uuid = request.GET.get("game_uuid")
        start_count = request.GET.get("start_count")
        end_count = request.GET.get("end_count")

        send_user = (
            UserPackageGoods.objects.filter(game_uuid=game_uuid)
            .filter(order_num__gt=start_count)
            .filter(order_num__lte=end_count)
            .extra(
                select={
                    "num": "UserOrder.num",
                    "money": "UserOrder.money",
                    "hunjing": "UserOrder.hunjing",
                    "recovery_price": "JuqiGood.recovery_price",
                },
                tables=["JuqiGood", "UserOrder"],
                where=[
                    "UserOrder.uuid=UserPackageGoods.order_uuid",
                    "JuqiGood.uuid=UserPackageGoods.good_uuid",
                ],
            )
            .values(
                "recovery_price",
                "money",
                "hunjing",
                "user_uuid",
                "num",
            )
        )

        _send = {}
        for feiqiu_item in send_user:
            if _send.get(str(feiqiu_item["user_uuid"])):
                _send[str(feiqiu_item["user_uuid"])] += (
                    (feiqiu_item["money"] + feiqiu_item["hunjing"]) / feiqiu_item["num"]
                ) - feiqiu_item["recovery_price"]
            else:
                _send[str(feiqiu_item["user_uuid"])] = (
                    (feiqiu_item["money"] + feiqiu_item["hunjing"]) / feiqiu_item["num"]
                ) - feiqiu_item["recovery_price"]

        a1 = dict(sorted(_send.items(), key=lambda x: x[1], reverse=True))
        new_dict = {"code": 0, "data": []}

        num = 0
        for key, value in a1.items():
            if value <= 0:
                break
            _u = Users.objects.filter(uuid=key).first()
            new_dict["data"].append(
                {
                    "user_nickname": _u.nickname,
                    "user_head_url": _u.head_url,
                    "value": value / 100,
                }
            )
            num += 1

        return JsonResponse(new_dict, status=status.HTTP_200_OK, safe=False)


class FeiqiuUserView(View):
    @login_auth
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        u: JuqiUser = kwargs["user_info"]
        if u.type != "wxuser":
            raise RightErr

        openid = u.openid

        game_uuid = request.GET.get("game_uuid")

        _game = WuxianshangGame.objects.filter(uuid=game_uuid).first()

        start_count = _game.count - _game.count % _game.feiqiu_num
        end_count = start_count + _game.feiqiu_num

        _user = Users.objects.filter(openid=openid).first()

        send_user = (
            UserPackageGoods.objects.filter(game_uuid=game_uuid)
            .filter(order_num__gt=start_count)
            .filter(order_num__lte=end_count)
            .extra(
                select={
                    "num": "UserOrder.num",
                    "money": "UserOrder.money",
                    "hunjing": "UserOrder.hunjing",
                    "recovery_price": "JuqiGood.recovery_price",
                },
                tables=["JuqiGood", "UserOrder"],
                where=[
                    "UserOrder.uuid=UserPackageGoods.order_uuid",
                    "JuqiGood.uuid=UserPackageGoods.good_uuid",
                ],
            )
            .values("recovery_price", "money", "hunjing", "user_uuid", "num")
        )

        _send = {}
        for feiqiu_item in send_user:
            if _send.get(str(feiqiu_item["user_uuid"])):
                _send[str(feiqiu_item["user_uuid"])] += (
                    (feiqiu_item["money"] + feiqiu_item["hunjing"]) / feiqiu_item["num"]
                ) - feiqiu_item["recovery_price"]
            else:
                _send[str(feiqiu_item["user_uuid"])] = (
                    (feiqiu_item["money"] + feiqiu_item["hunjing"]) / feiqiu_item["num"]
                ) - feiqiu_item["recovery_price"]

        a1 = dict(sorted(_send.items(), key=lambda x: x[1], reverse=True))

        new_dict = {
            "code": 0,
            "data": [],
            "now_user": [],
            "start_count": start_count + 1,
            "end_count": end_count,
        }

        num = 0
        for key, value in a1.items():
            if value <= 0 or num >= 5:
                break
            _u = Users.objects.filter(uuid=key).first()
            new_dict["data"].append(
                {
                    "user_nickname": _u.nickname,
                    "user_head_url": _u.head_url,
                    "value": value / 100,
                }
            )
            num += 1

        login_user = (
            UserPackageGoods.objects.filter(game_uuid=game_uuid)
            .filter(user_uuid=_user.uuid)
            .filter(order_num__gt=start_count)
            .filter(order_num__lte=end_count)
            .extra(
                select={
                    "num": "UserOrder.num",
                    "money": "UserOrder.money",
                    "hunjing": "UserOrder.hunjing",
                    "recovery_price": "JuqiGood.recovery_price",
                },
                tables=["JuqiGood", "UserOrder"],
                where=[
                    "UserOrder.uuid=UserPackageGoods.order_uuid",
                    "JuqiGood.uuid=UserPackageGoods.good_uuid",
                ],
            )
            .values("recovery_price", "money", "hunjing", "user_uuid", "num")
        )

        if not login_user:
            new_dict["now_user"].append(
                {
                    "feiqiu_cp": 0,
                    "count": 0,
                }
            )

        else:
            _send = {}
            for feiqiu_item in login_user:
                if _send.get(str(feiqiu_item["user_uuid"])):
                    _send[str(feiqiu_item["user_uuid"])] += (
                        (feiqiu_item["money"] + feiqiu_item["hunjing"])
                        / feiqiu_item["num"]
                    ) - feiqiu_item["recovery_price"]
                else:
                    _send[str(feiqiu_item["user_uuid"])] = (
                        (feiqiu_item["money"] + feiqiu_item["hunjing"])
                        / feiqiu_item["num"]
                    ) - feiqiu_item["recovery_price"]
            new_dict["now_user"].append(
                {
                    "feiqiu_cp": _send.get(str(_user.uuid)) / 100,
                    "count": login_user.count(),
                }
            )
        return JsonResponse(new_dict, status=status.HTTP_200_OK, safe=False)


# /api/wuxianshang/wuxianshangargs
class WuxianshangArgsView(View):
    def setup(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        super().setup(request, *args, **kwargs)

    @check_admin
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        #   req query params：
        #   - `many`  查询所有商品

        wxsa = get_wxs_args()
        wxsa_s = WuxianshangArgsSerializer(wxsa)
        return JsonResponse(wxsa_s.data, status=status.HTTP_200_OK, safe=False)

    @check_admin
    @transaction.atomic
    def put(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        WuxianshangArgs.objects.filter(id=1).select_for_update()
        body = JSONParser().parse(request)
        wxsa = get_wxs_args()

        wxsa_s = WuxianshangArgsSerializer(wxsa, data=body)
        wxsa_s.is_valid(raise_exception=True)
        wxsa_s.save()

        return JsonResponse(wxsa_s.data, status=status.HTTP_200_OK, safe=False)


class WxsRaffleIndexView(View):
    # @check_admin
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        game_id = request.GET.get("id", None)
        if game_id is None:
            raise ValueError

        wxs_game = WuxianshangGame.objects.filter(id=game_id).first()
        raffle_index = qjs_raffle.get_game_good_index(str(wxs_game.uuid))
        if raffle_index is None or raffle_index == "":
            raise ValueError

        _data = []
        for r in eval(raffle_index):
            good_name = r.get("good_name")
            index = r.get("index")
            a = f"赏品名称: {good_name}, 热度: {index}"
            _data.append(a)

        return JsonResponse(
            data=_data,json_dumps_params={'ensure_ascii':False}, status=status.HTTP_200_OK,safe=False
        )


class WxsRaffleFormat(View):
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        game_id = request.GET.get("id", None)
        if game_id is None:
            raise ValueError

        wxs_game = WuxianshangGame.objects.filter(id=game_id).first()

        qjs_raffle.del_keys(str(wxs_game.uuid))
        qjs_raffle.init_prize(str(wxs_game.uuid))
        qjs_raffle.format_prize(str(wxs_game.uuid))

        return JsonResponse(
            {"code": 0, "data": {}, "msg": ""}, status=status.HTTP_200_OK
        )


class TianjiangDetailView(View):
    def get(self, request: WSGIRequest, *args: Any, **kwargs: Any):
        game_uuid = request.GET.get("game_uuid")
        start_count = request.GET.get("start_count")
        end_count = request.GET.get("end_count")

        send_user = (
            UserPackageGoods.objects.filter(game_uuid=game_uuid)
            .filter(order_num__gte=start_count)
            .filter(order_num__lt=end_count)
            .extra(
                select={
                    "num": "UserOrder.num",
                    "recovery_price": "JuqiGood.recovery_price",
                },
                tables=["JuqiGood", "UserOrder"],
                where=[
                    "UserOrder.uuid=UserPackageGoods.order_uuid",
                    "JuqiGood.uuid=UserPackageGoods.good_uuid",
                ],
            )
            .values(
                "recovery_price",
                "user_uuid",
                "num",
            )
        )

        _send = {}
        for feiqiu_item in send_user:
            if _send.get(str(feiqiu_item["user_uuid"])):
                _send[str(feiqiu_item["user_uuid"])] += 1
            else:
                _send[str(feiqiu_item["user_uuid"])] = 1

        a1 = dict(sorted(_send.items(), key=lambda x: x[1], reverse=True))
        new_dict = {"code": 0, "data": []}

        for key, value in a1.items():
            _u = Users.objects.filter(uuid=key).first()
            new_dict["data"].append(
                {
                    "user_nickname": _u.nickname,
                    "user_head_url": _u.head_url,
                    "value": value,
                }
            )

        return JsonResponse(new_dict, status=status.HTTP_200_OK, safe=False)
